<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>

    <!-- 文章列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <ArticleItem
        v-for="obj in articleList"
        :key="obj.art_id"
        :articleObj="obj"
        :isShow="false"
        @click.native="itemClickFn(obj.art_id)"
      />
    </van-list>
  </div>
</template>

<script>
//.native修饰符，给组件内的根标签，绑定原始的click事件
import { searchResultsAPI } from "@/api";
import ArticleItem from "@/components/ArticleItem";
export default {
  name: "SearchResult",
  data() {
    return {
      page: 1,
      articleList: [], //搜索结果
      loading: false, //是否正在加载
      finished: false, //是否全部加载完成
    };
  },
  components: {
    ArticleItem,
  },
  async created() {
    //创建时获取搜索结果列表
    const res = await searchResultsAPI({
      page: this.page,
      q: this.$route.params.kw,
    });
    this.articleList = res.data.data.results;
    // console.log(this.articleList);
  },
  methods: {
    async onLoad() {
      //判断当前搜索结果列表是否有数据
      if (this.articleList.length > 0) {
        //加载获取数据
        this.page++;
        const res = await searchResultsAPI({
          page: this.page,
          q: this.$route.params.kw,
        });

        if (this.articleList.length === 0) {
          this.finished = true;
          return;
        }
        //合并保存数据
        this.articleList = [...this.articleList, ...res.data.data.results];
        this.loading = false;
      }
    },
    //文章点击事件
    itemClickFn(id) {
      this.$router.push({ path: `/detail?art_id=${id}` });
    },
  },
};
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
